package com.snowleopard.common.security;

import java.util.Collection;

import javax.persistence.NoResultException;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.snowleopard.findpeople.dao.account.UserDao;
import com.snowleopard.findpeople.entity.account.User;

@Component
public class UserDetailsServiceImpl implements org.springframework.security.core.userdetails.UserDetailsService {
	private static final Logger log = Logger.getLogger(UserDetailsServiceImpl.class);

	@Autowired
	UserDao userDao;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {

		User user = null;
		try {
			log.info("findUniqueBy: " + username);
			user = userDao.findUniqueBy("loginId", username);
			log.info("user: " + user);

			if (user == null) {
				throw new UsernameNotFoundException("not found user: " + username);
			}
			
		} catch (NoResultException ex) {
			throw new UsernameNotFoundException("not found user: " + username);
		}

		return new UserDetailsImpl(user);
	}

	/**
	 * 
	 * @param roles
	 * @return true if the user has one of the specified roles.
	 */
	public boolean hasAnyRole(String... roles) {

		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

		if (authentication != null) {
			Collection<GrantedAuthority> authorities = authentication.getAuthorities();
			for (GrantedAuthority authority : authorities) {
				String auth = authority.getAuthority();
				for (String role : roles) {
					if (role.equals(auth))
						return true;
				}
			}
		}

		return false;
	}

	/**
	 * 得到登陆成功的User
	 * 
	 * @return User
	 */
	public User getLoginUser() {

		boolean isAnonymous = hasAnyRole("ROLE_ANONYMOUS");
		if (isAnonymous)
			return null;

		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		String loginId = authentication.getName();
		log.info("login user: " + loginId);
		User user = userDao.findUniqueBy("loginId", loginId);

		return user;
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

}
